<template>
  <div class="nav-container">
    <div class="nav-bar">
      <!-- 左侧区域 -->
      <div class="nav-left">
        <img src="../assets/logo1.png" class="logo" alt="logo"/>
        <img src="../assets/文字.png" class="wenzi" alt="logo"/>
      </div>
      <div class="nav-center">
        <div ref="searchContainer">
            <div class="search-container">
                <div class="search-box">
                    <input
                            v-model="keyword"
                            @keyup.enter="handleSearch"
                            @focus="showHistory = true"
                            placeholder="请输入搜索内容"
                    />
                    <button @click="handleSearch">搜索</button>
                </div>
        </div>
          <div v-if="showHistory && historyList.length > 0"
               class="history-panel">
            <div class="history-header">
              <span>搜索历史</span>
              <button @click="clearAllHistory">清空</button>
            </div>
            <ul>
              <li v-for="(item, index) in historyList" :key="index">
                <span @click="selectHistory(item)">{{ item }}</span>
                <button @click="deleteHistory(index)">×</button>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <el-button
          plain
          @click="dialogFormVisible = true"
          v-if="!userName"
          style="position: relative;right: 30px"
      >登录</el-button>
      <!-- 右侧用户 -->
      <div class="nav-right" v-if="userName">

        <el-dropdown>
          <div class="user-wrapper" @mouseenter="hoverUser = true" @mouseleave="hoverUser = false">
            <el-avatar
                :size="40"
                :src="yhtx"
                :class="{'avatar-hover': hoverUser}"
            />
            <span class="username">{{ userInfo.yhnc }}</span>
            <el-icon class="arrow-icon"><arrow-down /></el-icon>
          </div>

          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="router.push('/home/showuser')">个人中心</el-dropdown-item>
              <el-dropdown-item divided>账户余额：￥{{userInfo.balance || 0}}</el-dropdown-item>
              <el-dropdown-item divided @click="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
  </div>
  <div class="auth-modal" v-if="dialogFormVisible">
    <div class="auth-container">
      <div class="auth-header">
        <button class="close-btn" @click="dialogFormVisible = false">×</button>
        <div class="auth-tabs">
          <button
              :class="{active: activeTab === 'login'}"
              @click="activeTab = 'login'"
          >登录</button>
          <button
              :class="{active: activeTab === 'register'}"
              @click="activeTab = 'register'"
          >注册</button>
        </div>
      </div>

      <!-- 登录表单 -->
      <form v-if="activeTab === 'login'" class="auth-form">
        <h3>欢迎回来</h3>
        <div class="form-group">
          <input
              type="text"
              v-model="form.yhzh"
              placeholder="手机号"
              class="form-input"
          >
        </div>
        <div class="form-group">
          <input
              type="password"
              v-model="form.pwd"
              placeholder="密码"
              class="form-input"
          >
        </div>
        <div class="form-footer">
          <a href="#" @click.prevent="activeTab = 'forgot'">忘记密码?</a>
        </div>
        <button
            type="button"
            @click="handleLoR"
            class="submit-btn"
        >立即登录</button>
      </form>

      <!-- 注册表单 -->
      <form v-else-if="activeTab === 'register'" class="auth-form">
        <h3>创建新账号</h3>
        <div class="form-group">
          <input
              type="text"
              v-model="r_form.yhzh"
              placeholder="手机号"
              class="form-input"
          >
        </div>
        <div class="form-group">
          <input
              type="password"
              v-model="r_form.pwd"
              placeholder="密码"
              class="form-input"
          >
        </div>
        <div class="form-group">
          <input
              type="password"
              v-model="r_form.cPwd"
              placeholder="确认密码"
              class="form-input"
          >
        </div>
        <div class="form-group">
          <input
              type="text"
              v-model="r_form.yhnc"
              placeholder="昵称"
              class="form-input"
          >
        </div>
        <button
            type="button"
            @click="handleLoR"
            class="submit-btn"
        >立即注册</button>
      </form>

      <!-- 忘记密码表单 -->
      <form v-else class="auth-form">
        <h3>重置密码</h3>
        <div class="form-group">
          <input
              type="text"
              v-model="forgotForm.yhzh"
              placeholder="注册手机号"
              class="form-input"
          >
        </div>
        <div class="form-group">
          <input
              type="password"
              v-model="forgotForm.pwd"
              placeholder="新密码"
              class="form-input"
          >
        </div>
        <div class="form-group">
          <input
              type="password"
              v-model="forgotForm.confirmPwd"
              placeholder="确认新密码"
              class="form-input"
          >
        </div>
        <div class="form-footer">
          <a href="#" @click.prevent="activeTab = 'login'">返回登录</a>
        </div>
        <button
            type="button"
            @click="handleLoR"
            class="submit-btn"
        >重置密码</button>
      </form>
    </div>
  </div>

</template>

<script setup>
import {Search, ArrowDown, Close} from '@element-plus/icons-vue'
import {onMounted, ref} from 'vue'
import axios from "axios";
import { useUserStore } from '../pages/stores/user.ts'
import router from "../router.js";
import { onClickOutside } from '@vueuse/core'
import {ElMessage} from "element-plus";
import ShowShouYe from "../pages/usershouye/ShowShouYe.vue";

const activeTab = ref('login')


const handleSearch = async () => {
  await router.push({
    path: '/',
    query: {key: keyword.value}
  })

  // 添加到历史记录（去重）
  if (keyword.value !== '' && !historyList.value.includes(keyword.value)) {
    historyList.value.unshift(keyword.value)
    // 限制最多保存10条记录
    if (historyList.value.length > 10) {
      historyList.value.pop()
    }
    saveHistory()
  }
  showHistory.value = false
}

const yhtx = ref('')
const searchContainer = ref(null)


onClickOutside(searchContainer, () => {
  showHistory.value = false
})
const userStore = useUserStore()

const form = ref({
  yhzh: '',
  pwd: ''
})
const r_form = ref({
  yhzh: '',
  pwd: '',
  cPwd: '',
  yhnc: ''
})
const forgotForm = ref({
  yhzh: '',
  pwd: '',
  confirmPwd: ''
})

const hoverUser = ref(false)
const userName = ref()
const tableVisible = ref(false)

const dialogFormVisible = ref(false)


const handleLoR = async () => {
  if (activeTab.value === 'login') {
    dialogFormVisible.value = false
    const {data} = await axios.post('/api/shenfen/login', form.value)
    console.log(data)
    if (data.code === 200) {
      ElMessage.success('登录成功')
      userStore.setUser(data.data)
      if(data.data.yhsf === '6') {
        await findsj(data.data.yhid)
      }
      if(data.data.yhsf === '9') {
        await findqs(data.data.yhid)
      }
      userName.value = data.data.yhnc
      window.location.reload()
    } else {
      ElMessage({type: 'error', message: '账号或密码错误'})
    }
  } else if (activeTab.value === 'register') {
    if (r_form.value.pwd !== r_form.value.cPwd) {
      ElMessage.error('两次密码不一致')
      return
    }
    const shanghaiDate = new Date(Date.now() + 8 * 60 * 60 * 1000);
    r_form.value.zcsj = shanghaiDate.toISOString().slice(0, 19).replace('T', ' ');
    const {data} = await axios.post('/api/shenfen', r_form.value)
    if (data.code === 200) {
      ElMessage.success('注册成功')
      activeTab.value = 'login'
      form.value.yhzh = r_form.value.yhzh
      form.value.pwd = r_form.value.pwd
    } else {
      ElMessage.error(data.message)
    }
  } else {
    if (forgotForm.value.pwd !== forgotForm.value.confirmPwd) {
      ElMessage.error('两次密码不一致')
      return
    }
    const {data} = await axios.post('/api/shenfen/forgot', forgotForm.value)
    if (data.code === 200) {
      ElMessage.success('重置成功')
      activeTab.value = 'login'

      form.value.yhzh = forgotForm.value.yhzh
      form.value.pwd = forgotForm.value.pwd
      forgotForm.value.yhzh = ''
      forgotForm.value.pwd = ''
      forgotForm.value.confirmPwd = ''
    } else {
      ElMessage.error(data.message)
    }
  }

}
const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || 'null'))
const findsj = async (yhid) => {
  const {data} = await axios.get(`/api/shangjia/yhid/${yhid}`)
  if(data.code === 200) {
    console.log(data.data)
    userInfo.value = JSON.parse(localStorage.getItem('userInfo'))
    userInfo.value.sjid = data.data.sjid
    userStore.setUser(userInfo.value)
  }
}
const findqs = async (yhid) => {
  const {data} = await axios.get(`/api/qishou/yhid/${yhid}`)
  if(data.code === 200) {
    console.log(data.data)
    userInfo.value = JSON.parse(localStorage.getItem('userInfo'))
    userInfo.value.qsid = data.data.qsid
    userStore.setUser(userInfo.value)
  }
}
const logout = () => {
  userStore.clearUser()
  router.push('/').then(() => {
    window.location.reload()
  })
  ElMessage.success('已退出登录')
}

// 搜索相关状态
const keyword = ref('')
const showHistory = ref(false)
const historyList = ref([])

// 加载搜索历史
const loadHistory = () => {
    const history = localStorage.getItem('searchHistory')
    historyList.value = history ? JSON.parse(history) : []
}

// 保存搜索历史
const saveHistory = () => {
    localStorage.setItem('searchHistory', JSON.stringify(historyList.value))
}

const showShouYeRef = ref()
// 执行搜索
const search = async () => {
    if (!keyword.value.trim()) {
        keyword.value = '全部'
    }

    // 添加到历史记录（去重）
    if (keyword.value !== '全部' && !historyList.value.includes(keyword.value)) {
        historyList.value.unshift(keyword.value)
        // 限制最多保存10条记录
        if (historyList.value.length > 10) {
            historyList.value.pop()
        }
        saveHistory()
    }
    await showShouYeRef.value.getSearch(keyword.value)
    showHistory.value = false
    keyword.value = ''
}

// 删除单条历史记录
const deleteHistory = (index) => {
    historyList.value.splice(index, 1)
    saveHistory()
}

// 清空所有历史记录
const clearAllHistory = () => {
    historyList.value = []
    localStorage.removeItem('searchHistory')
}

// 选择历史记录
const selectHistory = (item) => {
    keyword.value = item
    handleSearch();
}

onMounted(() => {
 loadHistory()
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || 'null')
  if (userInfo) {
    userName.value = userInfo.yhnc
    yhtx.value =  "http://localhost:8088/team/upload/"+userInfo.yhtx
  }
})
</script>

<style scoped>

.nav-container {
  z-index: 9999;
  position: fixed;
  top: 0;
  height: 50px;
  width: 100%;
  background: #f58147;
  padding: 10px 20px;
}

.nav-bar {
  display: flex;
  align-items: center;
  width: 100%;
  margin: 0 auto;
}

.nav-left {
  display: flex;
  align-items: center;
  min-width: 200px;
}

.logo {
  width: 60px;
  height: 60px;
  margin-right: 10px;
}

.wenzi {
  width: 100px;
  height: 60px;
}


.nav-center {
  flex: 1;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
}

.search-input {
  width: 400px;
}

.search-main {
  z-index: 999;
  position: absolute;
  width: 25.3%;
  height: 300px;
  background-color: white;
  border: 1px solid #f58147;
}

.history {
  margin: 10px auto;
  width: 90%;
  height: 40%;
  background-color: white;
}

.hotSearch {
  margin: 10px auto;
  width: 90%;
  height: 50%;
  background-color: white;
}

.nav-right {
  margin-right: 30px;
  display: flex;
  align-items: center;
  min-width: 150px;
  justify-content: flex-end;
}

.username {
  color: white;
}

.user-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s;
  outline: none;
}

.user-wrapper:hover {
  background-color: rgba(255, 255, 255, 0.15);
}

.user-wrapper:focus {
  outline: none;
}

.user-wrapper:hover .username {
  color: var(--el-color-primary-light-5);
}

.user-wrapper:hover .arrow-icon {
  transform: rotate(180deg);
}

:deep(.auth-dialog) {
  border-radius: 12px;
}

:deep(.el-tabs__item) {
  font-size: 18px;
  color: #666;
  padding: 0 30px;
}

:deep(.el-tabs__active-bar) {
  height: 3px;
  background: #f58147;
}

.auth-form {
  padding: 10px 40px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  padding: 0 40px 20px;
}

.cancel-btn {
  width: 120px;
  border-radius: 20px;
}

.confirm-btn {
  width: 120px;
  border-radius: 20px;
  background: #f58147;
  border-color: #f58147;
}

.confirm-btn:hover {
  opacity: 0.9;
}

.search-container {
    position: absolute;
    width: 300px;
    left: 40%;
    top: 20px;
    z-index: 10;
}

.search-box {
    display: flex;
}

.search-box input {
    flex: 1;
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 4px 0 0 4px;
}

.search-box button {
    padding: 8px 12px;
    background: #00a1d6;
    color: white;
    border: none;
    border-radius: 0 4px 4px 0;
    cursor: pointer;
}

.history-panel {
    position: absolute;
    top: 62px;
    left: 40%;
    width: 300px;
    background: white;
    border: 1px solid #eee;
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    z-index: 100;
}

.history-header {
    display: flex;
    justify-content: space-between;
    padding: 8px;
    border-bottom: 1px solid #eee;
}

.history-header button {
    background: none;
    border: none;
    color: #999;
    cursor: pointer;
}

.history-panel ul {
    list-style: none;
    padding: 0;
    margin: 0;
}

.history-panel li {
    display: flex;
    justify-content: space-between;
    padding: 8px;
    cursor: pointer;
}

.history-panel li:hover {
    background: #f5f5f5;
}

.history-panel li button {
    background: none;
    border: none;
    color: #999;
    cursor: pointer;
}

.dialog-footer {
    display: flex;
    justify-content: space-between;
    padding: 0 40px 20px;
}

.cancel-btn {
    width: 120px;
    border-radius: 20px;
}

.confirm-btn {
    width: 120px;
    border-radius: 20px;
    background: #f58147;
    border-color: #f58147;
}

.confirm-btn:hover {
    opacity: 0.9;
}

.auth-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 99999;
}

.auth-container {
  background: white;
  border-radius: 12px;
  width: 380px;
  padding: 30px;
  box-shadow: 0 5px 20px rgba(0,0,0,0.2);
  position: relative;
}

.auth-header {
  margin-bottom: 25px;
  text-align: center;
}

.close-btn {
  position: absolute;
  right: 15px;
  top: 15px;
  font-size: 24px;
  background: none;
  border: none;
  cursor: pointer;
  color: #999;
}

.auth-tabs {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.auth-tabs button {
  padding: 10px 25px;
  background: none;
  border: none;
  font-size: 16px;
  color: #666;
  cursor: pointer;
  position: relative;
}

.auth-tabs button.active {
  color: #f58147;
  font-weight: bold;
}

.auth-tabs button.active:after {
  content: '';
  position: absolute;
  bottom: -5px;
  left: 25%;
  width: 50%;
  height: 3px;
  background: #f58147;
  border-radius: 3px;
}

.auth-form h3 {
  text-align: center;
  margin-bottom: 25px;
  color: #333;
  font-size: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s;
}

.form-input:focus {
  border-color: #f58147;
  outline: none;
  box-shadow: 0 0 0 2px rgba(245,129,71,0.2);
}

.form-footer {
  text-align: right;
  margin-bottom: 20px;
}

.form-footer a {
  color: #f58147;
  text-decoration: none;
  font-size: 14px;
}

.submit-btn {
  width: 100%;
  padding: 12px;
  background: #f58147;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.submit-btn:hover {
  background: #e06d3a;
}


</style>
